//
// Created by denglibin on 2021/5/28.
//
#include <window.h>
#define FRAME_RATE 60 //帧率
/**
 * 初始化操作
 */
static void initSDL2(){
    //初始化，成功返回0
    if (SDL_Init(SDL_INIT_VIDEO)) {
        SDL_Log("Can not init video %s\n", SDL_GetError());
        exit(-1);
    }
}
/**
 * 事件循环
 */
void eventLoop(Window* window, Draw* draw, HandleEvent* handleEvent ){
    SDL_Event  event;
    window->lastTime = SDL_GetTicks();
    while (1)
    {//主消息循环
        uint32_t  begin = SDL_GetTicks();

        while (SDL_PollEvent(&event)){
            if(event.type == SDL_QUIT){
                return;
            }
            if(event.type == SDL_KEYDOWN && event.key.keysym.sym == SDLK_ESCAPE){
                return;
            }
            handleEvent(window, &event);
        }

        window->interval = SDL_GetTicks() - window->lastTime;
        window->lastTime = SDL_GetTicks();
        draw(window, &event);
        uint32_t  end = SDL_GetTicks();
        uint32_t  cost = end - begin;
        uint32_t per_frame_time = 1000 / FRAME_RATE;//每一帧耗时ms
        if (per_frame_time > cost){
            //减去循环体耗时，得到还应休眠的时间
            SDL_Delay(per_frame_time - cost);
        }

    }

}
/**
 * 创建窗口对象
 * @param width
 * @param height
 * @param title
 * @return
 */
Window * createWindow(int width, int height, const char* title){
    //初始化sdl2
    initSDL2();
    SDL_Window* win = SDL_CreateWindow(title,
                           SDL_WINDOWPOS_CENTERED,
                           SDL_WINDOWPOS_CENTERED,
                           width, height,
                                       SDL_WINDOW_HIDDEN);
    if (win == NULL) {
        SDL_Log("Can not create window %s\n", SDL_GetError());
        return NULL;
    }
    Window* window = (Window*)malloc(sizeof(Window));
    window->win = win;
    window->winRender = SDL_CreateRenderer(win, -1, SDL_RENDERER_ACCELERATED);
    window->winSurface = SDL_GetWindowSurface(win);

    return window;
}

/**
 * 释放空间
 * @param window
 */
void WindowFree(Window* window){
    SDL_DestroyRenderer(window->winRender);
    SDL_FreeSurface(window->winSurface);
    SDL_DestroyWindow(window->win);
    SDL_Quit();
    free(window);
}